use std::collections::{HashMap, HashSet};
use std::fs::File;
use std::io;
use std::io::BufRead;

pub fn converter(input: &str, tp: &str) -> String {
    if input.len() < 3 {
        return input.to_string();
    }
    let dict = generate_dict(tp);
    let un_changed_dict = generate_unchanged_dict();

    // find by word
    if let Some(word) = dict.get(input) {
        return word.to_string();
    }

    // find by contain word
    for key in un_changed_dict.iter() {
        if key.contains(input) {
            return input.to_string();
        }
    }
    for (key, value) in dict.iter() {
        if key.contains(input) {
            let start = key.find(input).unwrap();
            let end = start + input.len();
            return value[start..end].to_string();
        }
    }

    // find by char
    let mut result = vec![];
    'next_char: for char in input.chars() {
        for (key, value) in dict.iter() {
            if key.contains(char) {
                let start = key.find(char).unwrap();
                let end = start + char.to_string().len();
                result.push(value[start..end].to_string());
                continue 'next_char;
            }
        }
        result.push(char.to_string());
    }

    result.join("")
}

fn generate_dict(tp: &str) -> HashMap<String, String> {
    let mut dict = HashMap::new();
    let file = File::open("STPhrases.txt").unwrap();
    let reader = io::BufReader::new(file);
    for line in reader.lines() {
        let line = line.unwrap();
        let parts: Vec<&str> = line.split("\t").collect();
        if parts.len() == 2 {
            let simplified = parts[0].to_string();
            let traditional = parts[1].to_string();
            if tp == "s2t" {
                dict.insert(simplified.clone(), traditional.clone());
            } else {
                dict.insert(traditional.clone(), simplified.clone());
            }
        }
    }
    dict
}

fn generate_unchanged_dict() -> HashSet<String> {
    let mut dict = HashSet::new();
    let file = File::open("unchanged_word").unwrap();
    let reader = io::BufReader::new(file);
    for line in reader.lines() {
        let line = line.unwrap();
        dict.insert(line);
    }
    dict
}
